"""
Writing and content creation prompts for FastMCP
"""

from fastmcp import FastMCP, Context
from typing import List, Optional
from pydantic import Field


class WritingPrompts:
    """Writing and content creation prompts for FastMCP"""

    def __init__(self, mcp: FastMCP):
        self.mcp = mcp

    def register(self):
        """Register all writing prompts with the FastMCP server"""
        self.mcp.prompt(
            name="technical_documentation",
            description="Generate a prompt for creating technical documentation",
            tags={"writing", "documentation", "technical"},
        )(self.technical_documentation)

        self.mcp.prompt(
            name="blog_post",
            description="Generate a prompt for creating engaging blog posts",
            tags={"writing", "blog", "content"},
        )(self.blog_post)

        self.mcp.prompt(
            name="email_template",
            description="Generate a prompt for creating professional email templates",
            tags={"writing", "email", "communication"},
        )(self.email_template)

        self.mcp.prompt(
            name="creative_story",
            description="Generate a prompt for creative writing and storytelling",
            tags={"writing", "creative", "storytelling"},
        )(self.creative_story)

    def technical_documentation(
        self,
        subject: str = Field(description="What needs to be documented"),
        audience: str = Field(
            description="Target audience (developers, users, admins, etc.)"
        ),
        doc_type: str = Field(
            description="Type of documentation (API docs, user guide, tutorial, etc.)"
        ),
        complexity_level: str = Field(
            default="intermediate",
            description="Complexity level: beginner, intermediate, advanced",
        ),
        include_examples: bool = Field(
            default=True, description="Whether to include practical examples"
        ),
    ) -> str:
        """Generate a prompt for technical documentation creation."""

        examples_instruction = (
            """
6. **Practical Examples**
   - Include real-world usage examples
   - Provide code snippets where applicable
   - Show both basic and advanced use cases
   - Include troubleshooting examples"""
            if include_examples
            else ""
        )

        # Ensure string parameters are not FieldInfo objects
        complexity = (
            complexity_level if isinstance(complexity_level, str) else "intermediate"
        )

        complexity_guidance = {
            "beginner": "Use simple language, explain technical terms, provide step-by-step instructions",
            "intermediate": "Assume basic technical knowledge, focus on implementation details",
            "advanced": "Use technical terminology freely, focus on advanced concepts and optimization",
        }.get(complexity.lower(), "Adjust complexity as appropriate")

        prompt = f"""Create comprehensive technical documentation for: **{subject}**

**Target Audience**: {audience}
**Documentation Type**: {doc_type}
**Complexity Level**: {complexity_level} - {complexity_guidance}

**Documentation Structure**:

1. **Overview and Introduction**
   - Clear explanation of what {subject} is and its purpose
   - Key benefits and use cases
   - Prerequisites and requirements
   - Quick start guide or summary

2. **Getting Started**
   - Installation or setup instructions
   - Initial configuration steps
   - Basic usage walkthrough
   - First successful implementation

3. **Detailed Documentation**
   - Comprehensive feature coverage
   - API reference or command syntax
   - Configuration options and parameters
   - Advanced features and capabilities

4. **Best Practices**
   - Recommended approaches and patterns
   - Performance considerations
   - Security guidelines
   - Common pitfalls to avoid

5. **Troubleshooting**
   - Common issues and their solutions
   - Error messages and their meanings
   - Debugging techniques
   - Where to get additional help{examples_instruction}

7. **Reference Materials**
   - Glossary of terms
   - Related resources and links
   - Version compatibility information
   - Change log or release notes

**Writing Guidelines**:
- Use clear, concise language appropriate for {audience}
- Structure information logically with proper headings
- Include diagrams or flowcharts where helpful
- Ensure all instructions are testable and accurate
- Maintain consistency in terminology and formatting

Please create documentation that is both comprehensive and easy to follow."""

        return prompt

    async def blog_post(
        self,
        ctx: Context,
        topic: str = Field(description="Main topic or subject of the blog post"),
        target_audience: str = Field(description="Who is the intended audience"),
        tone: str = Field(
            default="professional",
            description="Tone of the post (professional, casual, humorous, etc.)",
        ),
        post_length: str = Field(
            default="medium",
            description="Desired length: short (500-800), medium (800-1500), long (1500+)",
        ),
        include_seo: bool = Field(
            default=True, description="Whether to optimize for SEO"
        ),
    ) -> str:
        """Generate a prompt for blog post creation."""

        await ctx.info(f"Creating blog post prompt for topic: {topic}")

        # Ensure string parameters are not FieldInfo objects
        post_len = post_length if isinstance(post_length, str) else "medium"

        length_guidance = {
            "short": "500-800 words - focus on one key point with practical takeaways",
            "medium": "800-1500 words - explore the topic thoroughly with examples and insights",
            "long": "1500+ words - comprehensive deep-dive with multiple sections and detailed analysis",
        }.get(post_len.lower(), "Adjust length as appropriate")

        seo_section = (
            """
7. **SEO Optimization**
   - Include relevant keywords naturally throughout the content
   - Create an engaging meta description (150-160 characters)
   - Use header tags (H2, H3) for proper structure
   - Include internal and external links where appropriate
   - Add alt text descriptions for any images mentioned"""
            if include_seo
            else ""
        )

        prompt = f"""Write an engaging blog post about: **{topic}**

**Target Audience**: {target_audience}
**Tone**: {tone}
**Length**: {post_length.title()} ({length_guidance})

**Blog Post Structure**:

1. **Compelling Headline**
   - Create an attention-grabbing title that clearly conveys the value
   - Consider using numbers, questions, or power words
   - Keep it under 60 characters for optimal display

2. **Hook and Introduction**
   - Start with a compelling hook (question, statistic, story, or bold statement)
   - Clearly establish what the post will cover
   - Explain why this matters to the reader
   - Preview the key takeaways

3. **Main Content Sections**
   - Break content into digestible sections with clear subheadings
   - Use a logical flow that builds understanding
   - Include specific examples, case studies, or anecdotes
   - Support claims with data or expert opinions

4. **Practical Value**
   - Provide actionable advice or insights
   - Include step-by-step instructions where applicable
   - Offer tools, resources, or templates
   - Share personal experiences or lessons learned

5. **Visual Elements**
   - Suggest where images, infographics, or charts would enhance understanding
   - Recommend bullet points or numbered lists for easy scanning
   - Consider adding quotes or callout boxes for emphasis

6. **Strong Conclusion**
   - Summarize the key points covered
   - Reinforce the main takeaway or call-to-action
   - Encourage reader engagement (comments, shares, next steps)
   - Leave readers with something memorable{seo_section}

**Writing Guidelines**:
- Write in a {tone} tone that resonates with {target_audience}
- Use short paragraphs and sentences for better readability
- Include transitional phrases to maintain flow
- Address the reader directly using "you" when appropriate
- Back up claims with credible sources or examples

Create a blog post that provides genuine value and encourages reader engagement."""

        return prompt

    def email_template(
        self,
        email_purpose: str = Field(
            description="Purpose of the email (follow-up, proposal, announcement, etc.)"
        ),
        recipient_type: str = Field(
            description="Type of recipient (client, colleague, customer, etc.)"
        ),
        formality_level: str = Field(
            default="professional",
            description="Formality level: formal, professional, casual",
        ),
        include_call_to_action: bool = Field(
            default=True, description="Whether to include a clear call-to-action"
        ),
        email_length: str = Field(
            default="concise", description="Preferred length: brief, concise, detailed"
        ),
    ) -> str:
        """Generate a prompt for email template creation."""

        # Ensure string parameters are not FieldInfo objects
        formality = (
            formality_level if isinstance(formality_level, str) else "professional"
        )
        email_len = email_length if isinstance(email_length, str) else "concise"

        formality_guidance = {
            "formal": "Use formal language, proper titles, and traditional business etiquette",
            "professional": "Use professional but friendly tone, appropriate for business communication",
            "casual": "Use conversational tone while maintaining professionalism",
        }.get(formality.lower(), "Use appropriate formality level")

        length_guidance = {
            "brief": "Keep to essential points only (2-3 short paragraphs)",
            "concise": "Include necessary details while staying focused (3-4 paragraphs)",
            "detailed": "Provide comprehensive information and context (multiple paragraphs)",
        }.get(email_len.lower(), "Adjust length as needed")

        cta_section = (
            """
6. **Call-to-Action**
   - Include a clear, specific action you want the recipient to take
   - Make it easy for them to respond or take the next step
   - Provide deadlines or timelines if applicable
   - Offer multiple ways to respond if appropriate"""
            if include_call_to_action
            else ""
        )

        prompt = f"""Create a professional email template for: **{email_purpose}**

**Recipient Type**: {recipient_type}
**Formality Level**: {formality_level} - {formality_guidance}
**Length**: {email_length} - {length_guidance}

**Email Template Structure**:

1. **Subject Line**
   - Create a clear, compelling subject line that accurately reflects the content
   - Keep it under 50 characters for mobile optimization
   - Consider urgency or benefit if appropriate
   - Avoid spam trigger words

2. **Opening/Greeting**
   - Use appropriate salutation for the {formality_level} level
   - Personalize when possible with recipient's name
   - Include brief context or reference if this is a follow-up

3. **Purpose Statement**
   - Clearly state the reason for the email in the first paragraph
   - Be direct and specific about what you're communicating
   - Set appropriate expectations for the rest of the email

4. **Main Content**
   - Organize information logically and clearly
   - Use bullet points or numbered lists for multiple items
   - Include all necessary details while staying {email_length}
   - Support your points with relevant information

5. **Professional Closing**
   - Summarize next steps or key takeaways
   - Express appreciation where appropriate
   - Use professional sign-off appropriate for {formality_level} level{cta_section}

7. **Additional Elements**
   - Suggest appropriate signature block elements
   - Include any necessary disclaimers or legal text
   - Consider attachments or links that might be needed

**Writing Guidelines**:
- Match the tone to the relationship with {recipient_type}
- Use active voice and clear, direct language
- Proofread for grammar, spelling, and clarity
- Ensure the email serves its intended purpose effectively
- Make it easy for the recipient to understand and respond

Create an email template that is professional, clear, and achieves its intended purpose."""

        return prompt

    def creative_story(
        self,
        genre: str = Field(description="Story genre (mystery, sci-fi, romance, etc.)"),
        setting: str = Field(description="Where and when the story takes place"),
        main_character: str = Field(description="Description of the protagonist"),
        conflict_type: str = Field(description="Type of central conflict or challenge"),
        story_length: str = Field(
            default="short",
            description="Target length: flash (under 500), short (500-2000), medium (2000-5000)",
        ),
        themes: List[str] = Field(
            default=[], description="Themes to explore in the story"
        ),
    ) -> str:
        """Generate a prompt for creative story writing."""

        # Ensure string parameters are not FieldInfo objects
        story_len = story_length if isinstance(story_length, str) else "short"

        length_guidance = {
            "flash": "Under 500 words - focus on a single moment or revelation",
            "short": "500-2000 words - develop a complete story arc with character development",
            "medium": "2000-5000 words - allow for more complex plot and character development",
        }.get(story_len.lower(), "Adjust length as appropriate")

        # Ensure themes is a list, not a FieldInfo object
        themes_list = themes if isinstance(themes, list) else []
        themes_text = (
            "\n".join(f"- {theme}" for theme in themes_list)
            if themes_list
            else "Develop themes organically through the story"
        )

        prompt = f"""Write a creative {genre} story with the following elements:

**Genre**: {genre}
**Setting**: {setting}
**Main Character**: {main_character}
**Central Conflict**: {conflict_type}
**Target Length**: {story_length} ({length_guidance})

**Themes to Explore**:
{themes_text}

**Story Development Framework**:

1. **Opening Hook**
   - Start with an engaging scene that draws readers in immediately
   - Establish the setting and introduce the main character quickly
   - Create intrigue or tension from the very beginning
   - Set the tone appropriate for the {genre} genre

2. **Character Development**
   - Give the protagonist clear motivations and goals
   - Show their personality through actions and dialogue
   - Include flaws or vulnerabilities that make them relatable
   - Develop supporting characters that serve the story

3. **Plot Structure**
   - Establish the central conflict early in the story
   - Build tension progressively toward a climax
   - Include obstacles and complications that test the character
   - Ensure each scene advances the plot or develops character

4. **Setting and Atmosphere**
   - Bring {setting} to life through vivid, sensory descriptions
   - Use the environment to enhance mood and tension
   - Make the setting integral to the plot when possible
   - Balance description with action and dialogue

5. **Dialogue and Voice**
   - Create distinct voices for different characters
   - Use dialogue to reveal character and advance plot
   - Ensure conversations feel natural and purposeful
   - Match the dialogue style to the {genre} genre

6. **Resolution**
   - Resolve the central conflict in a satisfying way
   - Show how the character has changed or grown
   - Tie up loose ends while leaving some room for interpretation
   - End with impact that resonates with the themes

**Writing Guidelines**:
- Show rather than tell whenever possible
- Use active voice and strong verbs
- Create scenes that engage multiple senses
- Maintain consistency in point of view and tense
- Edit for clarity, pace, and emotional impact

Write a compelling story that fully explores the {conflict_type} while staying true to the {genre} genre conventions."""

        return prompt
